package com.cory.boot.base;

import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import com.alibaba.fastjson.JSONObject;
import com.cory.boot.domain.bean.Result;
import com.cory.boot.support.mybatis.interceptor.AllPageTotalHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableMap;

/**
 * 
 */
public abstract class BaseController {
    @Autowired
    protected HttpServletRequest request;
    
	/**
     * 验证参数不能为空
     * @param objects
     */
	@SuppressWarnings("rawtypes")
	protected final void assertNotNull(Object... objects) {
        for (Object object : objects) {
            Assert.notNull(object, "object can not be null");
            
            if (object instanceof String)
                Assert.hasLength((String)object, "string can not be empty");
            
            else if (object instanceof Collection)
                Assert.notEmpty((Collection)object, "collection can not be empty");
        }
    }
	
	protected final Page<?> startPage() {
	    String pageNum = request.getParameter("pageNum");
	    String pageSize = request.getParameter("pageSize");
	    
	    return PageHelper.startPage(StringUtils.isNotBlank(pageNum) ? Integer.valueOf(pageNum) : 1, 
	            StringUtils.isNotBlank(pageSize) ? Integer.valueOf(pageSize) : BaseConstants.PAGE_SIZE);
	}
	
	protected final void startOrderByPage(Model model) {
	    Page<?> page = startPage();
	    String pageOrderBy = request.getParameter("pageOrderBy");
	    if (StringUtils.isNotBlank(pageOrderBy)) {
	        page.setOrderBy(pageOrderBy);
	        model.addAttribute("pageOrderBy", pageOrderBy);
	    }
    }
	
	protected final void startPageTotal(String... columns) {
	    AllPageTotalHelper.start(columns);
    }
	
	protected final void pageTotalData(Model model, List<?> data) {
	    if (data != null && data.size() > 0) {
	        model.addAttribute("pageTotalData", JSONObject.toJSONString(data.get(0)));
	    } else {
	        model.addAttribute("pageTotalData", "{}");
	    }
	}
	
	protected final Result<?> ajaxList(Collection<?> list) {
        return Result.success().data(ImmutableMap.of("list", list, "count", list.size()));
    }
	
	protected final Result<?> ajaxPage(PageInfo<?> page) {
        return Result.success().data(ImmutableMap.of("list", page.getList(), "total", page.getTotal(), "pages", page.getPages()));
    }
}
